package com.gh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gh.common.exception.Assert;
import com.gh.common.result.ResponseEnum;
import com.gh.entity.*;
import com.gh.enums.*;
import com.gh.mapper.*;
import com.gh.service.BorrowInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.service.BorrowerService;
import com.gh.service.LendService;
import com.gh.vo.BorrowInfoApprovalVo;
import com.gh.vo.BorrowerDetailVo;
import com.gh.vo.BorrowerVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author Eric
 * @since 2021-09-06
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private IntegralGradeMapper integralGradeMapper;

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private BorrowerMapper borrowerMapper;

    @Autowired
    private BorrowerService borrowerService;

    @Autowired
    private LendService lendService;

    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        //获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        //根据积分查询额度
        LambdaQueryWrapper<IntegralGrade> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.le(IntegralGrade::getIntegralStart, userInfo.getIntegral())
                .ge(IntegralGrade::getIntegralEnd, userInfo.getIntegral());
        IntegralGrade integralGrade = integralGradeMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(integralGrade)) {
            return new BigDecimal("0");
        }
        return integralGrade.getBorrowAmount();
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        //获取用户信息
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //判断用户绑定状态
        Assert.isTrue(
                userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_BIND_ERROR
        );
        //判断用户信息是否审核通过
        Assert.isTrue(
                userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_AMOUNT_ERROR
        );
        //判断借款人额度是否充足
        BigDecimal borrowAmount = this.getBorrowAmount(userId);//获取借款额度
        Assert.isTrue(
                borrowAmount.intValue() >= borrowInfo.getAmount().intValue(),
                ResponseEnum.USER_AMOUNT_LESS_ERROR
        );
        //存储borrowInfo数据
        borrowInfo.setUserId(userId);
        //百分数转小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        //设置状态
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);
    }

    @Override
    public Integer getBorrowInfoStatus(Long userId) {
        LambdaQueryWrapper<BorrowInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BorrowInfo::getUserId, userId);
        BorrowInfo borrowInfo = baseMapper.selectOne(lambdaQueryWrapper);
        if (borrowInfo == null) {
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        return borrowInfo.getStatus();
    }

    @Override
    public List<BorrowInfo> selectList() {
        List<BorrowInfo> borrowInfoList = baseMapper.selectList(null);
        borrowInfoList.forEach(borrowInfo -> {
            Long userId = borrowInfo.getUserId();
            UserInfo userInfo = userInfoMapper.selectById(userId);
            borrowInfo.setName(userInfo.getName());
            borrowInfo.setMobile(userInfo.getMobile());
            String returnMethod = this.findDictByDictCodeAndValue(DictEnum.RETURN_METHOD.getDictCode(), borrowInfo.getReturnMethod());
            String moneyUse = this.findDictByDictCodeAndValue(DictEnum.MONEY_USER.getDictCode(), borrowInfo.getMoneyUse());
            String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
            borrowInfo.getParam().put("returnMethod", returnMethod);
            borrowInfo.getParam().put("moneyUse", moneyUse);
            borrowInfo.getParam().put("status", status);
        });
        return borrowInfoList;
    }

    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {
        //查询借款信息
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        //还款方式
        String returnMethod = this.findDictByDictCodeAndValue(DictEnum.RETURN_METHOD.getDictCode(), borrowInfo.getReturnMethod());
        String moneyUse = this.findDictByDictCodeAndValue(DictEnum.MONEY_USER.getDictCode(), borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod", returnMethod);
        borrowInfo.getParam().put("moneyUse", moneyUse);
        borrowInfo.getParam().put("status", status);
        Long userId = borrowInfo.getUserId();
        //查询借款对象
        LambdaQueryWrapper<Borrower> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Borrower::getUserId, userId);
        Borrower borrower = borrowerMapper.selectOne(lambdaQueryWrapper);
        BorrowerDetailVo borrowerDetail = borrowerService.getBorrowerDetailVoById(borrower.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("borrowInfo", borrowInfo);
        map.put("borrower", borrowerDetail);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowInfoApprovalVo borrowInfoApprovalVo) throws ParseException {
        //修改借款审批状态 borrow_info
        Long borrowInfoId = borrowInfoApprovalVo.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(borrowInfoApprovalVo.getStatus());
        baseMapper.updateById(borrowInfo);
        //如果审核通过，产生新的标的记录 lend
        if (borrowInfoApprovalVo.getStatus() == BorrowInfoStatusEnum.CHECK_OK.getStatus()) {
            lendService.createLend(borrowInfoApprovalVo, borrowInfo);
        }
    }

    /**
     * 通过dictcode和value查询name
     *
     * @param dictCode
     * @param value
     * @return
     */
    private String findDictByDictCodeAndValue(String dictCode, Integer value) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getDictCode, dictCode);
        Dict parentDict = dictMapper.selectOne(lambdaQueryWrapper);
        if (parentDict == null) {
            return "";
        }
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getParentId, parentDict.getId());
        lambdaQueryWrapper.eq(Dict::getValue, value);
        Dict dict = dictMapper.selectOne(lambdaQueryWrapper);
        if (dict == null) {
            return "";
        }
        return dict.getName();
    }
}
